package com.uit.httt04.duongvanlam.facedetection.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.content.res.AssetManager;

public class ClassFile
{
	public static File getCascadeXmlFile(Context context) throws Exception
	{
		try
		{
			AssetManager assetManager = context.getResources().getAssets();
			InputStream inputStream = assetManager.open(Configuration.xmlFileName);
			File xmlFile = ClassFile.createFileFromInputStream(context, inputStream, Configuration.xmlFolderPath, Configuration.xmlFileName);
			return xmlFile;
		}
		catch (Exception e)
		{
			throw e;
		}
	}

	private static File createFileFromInputStream(Context context, InputStream inputStream, String outputFolderPath, String outputFileName) throws IOException, Exception
	{
		try
		{
			// <-- Create folder
			File folder = new File(outputFolderPath);
			if (folder.exists() == false)
				folder.mkdirs();
			// Create folder -->

			File result = new File(folder, outputFileName);
			if (result.exists() == true)
				return result;
			else
			{
				OutputStream outputStream = null;
				byte[] buffer = null;
				int length;

				try
				{
					result.createNewFile();
					//
					outputStream = new FileOutputStream(result);
					buffer = new byte[1024];
					length = 0;
					//
					while ((length = inputStream.read(buffer)) > 0)
					{
						outputStream.write(buffer, 0, length);
					}
				}
				finally
				{
					if (outputStream != null)
						outputStream.close();
					if (inputStream != null)
						inputStream.close();
					if (buffer != null)
						buffer = null;
				}
				return result;
			}
		}
		catch (IOException iOException)
		{
			throw iOException;
		}
		catch (Exception exception)
		{
			throw exception;
		}
	}

	public static void DeleteRecursive(File fileOrDirectory) throws Exception
	{
		try
		{
			if (fileOrDirectory.isDirectory())
				for (File child : fileOrDirectory.listFiles())
					DeleteRecursive(child);

			fileOrDirectory.delete();
		}
		catch (Exception e)
		{
			throw e;
		}
	}

	public static void CreateAppFolder()
	{
		//
		File appFolder = new File(Configuration.appFolderPath);
		if (appFolder.exists() == false)
			appFolder.mkdirs();
		//
		File trainingFolder = new File(Configuration.trainingFolderPath);
		if (trainingFolder.exists() == false)
			trainingFolder.mkdirs();
		//
		File detectionFolder = new File(Configuration.detectionFolderPath);
		if (detectionFolder.exists() == false)
			detectionFolder.mkdirs();
		//
		File logFolder = new File(Configuration.logFolderPath);
		if (logFolder.exists() == false)
			logFolder.mkdirs();
	}
}
